package com.demo.common.webSocket;

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ServerEndpoint(value = "/socketServer/{userId}")
@Component
public class SocketServer {

	private final static int SYSTEM_ID = 0;

	private Session session;
	private static Map<Integer, Session> sessionPool = new HashMap<>();
	private static Map<String, Integer> sessionIds = new HashMap<>();

	/**
	 * 用户连接时触发
	 * @param session
	 * @param userId
	 */
	@OnOpen
	public void open(Session session, @PathParam(value="userId")Integer userId){
		this.session = session;
		sessionPool.put(userId, session);
		sessionIds.put(session.getId(), userId);
	}

	/**
	 * 收到信息时触发
	 * @param message
	 */
	@OnMessage
	public void onMessage(String message){
		sendMessage(sessionIds.get(session.getId()) + "<--" + message, SYSTEM_ID);
		System.out.println("发送人:" + sessionIds.get(session.getId()) + "内容:" + message);
	}

	/**
	 * 连接关闭触发
	 */
	@OnClose
	public void onClose(){
		sessionPool.remove(sessionIds.get(session.getId()));
		sessionIds.remove(session.getId());
	}

	/**
	 * 发生错误时触发
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		error.printStackTrace();
	}

	/**
	 * 信息发送的方法
	 * @param message
	 * @param userId
	 */
	public static void sendMessage(String message, Integer userId){
		Session s = sessionPool.get(userId);
		if(s != null){
			try {
				s.getBasicRemote().sendText(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取当前连接数
	 * @return
	 */
	public static int getOnlineNum(){
		if(sessionIds.values().contains(SYSTEM_ID)) {
			return sessionPool.size() - 1;
		}
		return sessionPool.size();
	}

	/**
	 * 获取在线用户名以逗号隔开
	 * @return
	 */
	public static String getOnlineUsers(){
		StringBuilder userIdStr = new StringBuilder();
		for (String key : sessionIds.keySet()) {
			// 去除系统
			if (SYSTEM_ID != sessionIds.get(key)) {
				userIdStr.append(",").append(sessionIds.get(key));
			}
		}
		return userIdStr.substring(1);
	}

	/**
	 * 信息群发
	 * @param msg
	 */
	public static void sendAll(String msg) {
		for (String key : sessionIds.keySet()) {
			if (SYSTEM_ID != sessionIds.get(key)) {
				sendMessage(msg, sessionIds.get(key));
			}
		}
	}

	/**
	 * 多个人发送给指定的几个用户
	 * @param msg
	 * @param persons  用户s
	 */
	public static void sendMany(String msg, List<Integer> persons) {
		for (Integer userId : persons) {
			sendMessage(msg, userId);
		}
	}
}
